/**
 * 
 */
window.addEventListener("load", onload);
var pageNumber=0;
var iid;
var inter=1000;

function onload(){
	var btnStart=document.querySelector("#btnStart");
	btnStart.addEventListener("click", startCount, false);
	var btnStop=document.querySelector("#btnStop");
	btnStop.addEventListener("click", pauseCount, false);
	var btnReset=document.querySelector("#btnReset");
	btnReset.addEventListener("click", resetCount, false);
	var btnSet=document.querySelector("#btnSet");
	btnSet.addEventListener("click", setInter, false);
	
	updateControlState();
}

function setInter() {
	pauseCount();
	//if(iid>0)return; //guard condition	
	inter=document.querySelector("#interval").value;
	iid=setInterval(incrementPageNumber, inter);
	updateControlState();
	
}
function startCount(){	
	if(iid>0)return; //guard condition	
	iid=setInterval(incrementPageNumber, 1000);
	updateControlState();
	
}

function incrementPageNumber(){
	pageNumber++;	
	updateView();	
}

function updateView(){
	document.querySelector("#p").innerHTML=pageNumber;
}
//MVC - model, view, controller

function pauseCount(){
	clearTimeout(iid);
	iid=0;
	
	updateControlState();
}
function resetCount(){
	//pauseCount();
	pageNumber=0;
	updateView();
	
	updateControlState();
}

function isRunning(){
	return iid>0;
}

function updateControlState(){
	var btnStart=document.querySelector("#btnStart");
	var btnStop=document.querySelector("#btnStop");
	var btnReset=document.querySelector("#btnReset");
	
	btnStart.disabled = isRunning();
	btnStop.disabled = !isRunning();
	btnReset.disabled = !isRunning();
}